from allauth.account.views import SignupView
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.utils.crypto import get_random_string

User = get_user_model()

from bookmarks.models import Bookmark
from .forms import UserForm, ProfileForm, InvitationForm
from .models import Friendship, Invitation


@login_required
def profile(request):
    """用户个人主页页面"""
    return render(request, 'account/profile.html')


@login_required
def account_settings(request):
    """用户设置页面"""

    # instance关键字参数自动填充原来的数据
    form = UserForm(instance=request.user)
    profile_form = ProfileForm(instance=request.user.profile)

    if request.method == 'POST':
        form = UserForm(
            data=request.POST,
            files=request.FILES,
            instance=request.user
        )
        profile_form = ProfileForm(
            data=request.POST,
            files=request.FILES,
            instance=request.user.profile
        )
        if form.is_valid() and profile_form.is_valid():
            form.save()
            profile_form.save()
            return redirect(reverse('account_profile'))

    context = {'form': form, 'profile_form': profile_form}
    return render(request, 'account/account_settings.html', context)


def friends(request, username):
    """获取用户`username`的所有的朋友
    """
    user = get_object_or_404(User, username=username)
    # 朋友列表
    friend_list = [friendship.to_friend for friendship in user.from_friendship_set.all()]
    # 获取朋友的书签
    friend_bookmarks = Bookmark.objects.filter(user__in=friend_list).order_by('-id')
    context = {
        'username': username,
        'friend_list': friend_list,
        'bookmarks': friend_bookmarks,
    }
    return render(request, 'account/friends.html', context=context)


@login_required
def new_friend(request):
    """添加好友"""
    if 'username' not in request.GET:
        raise Http404
    friend = get_object_or_404(User, username=request.GET['username'])
    Friendship.objects.create(from_friend=request.user, to_friend=friend)
    return redirect(reverse('friends', args=(request.user.username,)))


@login_required
def invite_friend(request):
    """邀请页面"""
    form = InvitationForm()
    if request.method == 'POST':
        form = InvitationForm(request.POST)
        if form.is_valid():
            invitation = Invitation(
                name=form.cleaned_data['name'],
                email=form.cleaned_data['email'],
                code=get_random_string(20),
                sender=request.user
            )
            invitation.save()
            invitation.send()
            messages.success(request, '邀请邮件发送成功！')
            return redirect(reverse('bookmark_list'))
    context = {'form': form}
    return render(request, 'account/invitation.html', context=context)


def friend_accept(request, code):
    """接受邀请，往回话中添加数据"""
    invitation = get_object_or_404(Invitation, code__exact=code)
    request.session['invitation'] = invitation.id
    return redirect(reverse('account_signup'))


class Signup(SignupView):
    """重写allauth SignupView注册功能，添加增加好友功能"""

    def form_valid(self, form):
        resp = super().form_valid(form)

        if 'invitation' in self.request.session:
            invitation = Invitation.objects.get(id=self.request.session['invitation'])

            # 添加好友是相互的
            friendship = Friendship(from_friend=self.user, to_friend=invitation.sender)
            friendship.save()
            friendship = Friendship(from_friend=invitation.sender, to_friend=self.user)
            friendship.save()

            # 删除数据库额session中的邀请数据
            invitation.delete()
            del self.request.session['invitation']

        return resp